package com.example.tsproject.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.tsproject.Utils.ThreadLocalUtil;
import com.example.tsproject.entity.Assignments;
import com.example.tsproject.entity.AssignmentsWithStudentName;
import com.example.tsproject.entity.Questions;
import com.example.tsproject.entity.Students;
import com.example.tsproject.mapper.AnswersMapper;
import com.example.tsproject.mapper.AssignmentquestionsMapper;
import com.example.tsproject.mapper.QuestionsMapper;
import com.example.tsproject.service.AssignmentsService;
import com.example.tsproject.mapper.AssignmentsMapper;
import com.example.tsproject.service.StudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* @author DELL
* @description 针对表【assignments】的数据库操作Service实现
* @createDate 2025-03-11 10:52:34
*/
@Service
public class AssignmentsServiceImpl extends ServiceImpl<AssignmentsMapper, Assignments>
    implements AssignmentsService {
    @Autowired
    private AssignmentsMapper assignmentsMapper;
    @Autowired
    private StudentsService studentsService;
    @Autowired
    private AssignmentquestionsMapper assignmentquestionsMapper;
    @Autowired
    private AnswersMapper answersMapper;
    @Autowired
    private QuestionsMapper questionsMapper;

    @Override
    public List<Assignments> getExerciseList(String publisher_Number) {
        return assignmentsMapper.getExerciseList(publisher_Number);
    }

    @Override
    public List<Assignments> getHomeworkList(String stuNumber) {
        return assignmentsMapper.getHomeworkList(stuNumber);

    }

    @Override
    public List<Assignments> getAssignmentsList(String tNumber) {
        return assignmentsMapper.getAssignmentsList(tNumber);
    }

    @Override
    public List<Assignments> getStuWorkListByClass(String tNumber, String classNumber, String name) {
        return assignmentsMapper.getStuWorkListByClass(tNumber, classNumber, name);
    }

    @Override

    public boolean createAssignmentForStudent(String studentNumber, String name, String assignmentType, List<Questions> questions, Date startTime, Date endTime) {
        // Find student by student number
        System.out.println(questions.size());
        Students student = studentsService.findStudents(studentNumber);
        if (student == null) {
            return false;
        }
        Assignments assignment = new Assignments();
        assignment.setPublisher_number(studentNumber);
        assignment.setStuNum(student.getStudent_number());
        assignment.setClass_number(student.getStuclass());
        assignment.setName(name);
        assignment.setAssignment_type(assignmentType);
        assignment.setStart_time(startTime);
        assignment.setEnd_time(endTime);
        assignment.setScore(BigDecimal.valueOf(0.0));
        assignment.setIsSubmit('n');
        assignment.setIsUse('y');
        // Insert into Assignments table
        assignmentsMapper.insertAssignment(assignment);
        Integer assignmentId = assignment.getId(); // 获取生成的 ID
        System.out.println(assignmentId + ")))))))))))))))");
        // Insert into AssignmentQuestions table
        for (Questions question : questions) {
            assignmentquestionsMapper.insertAssignmentQuestion(assignmentId, question.getId());
        }

        return true;
    }

    @Override

    public boolean assignToClass(String type,String name, List<Questions> questions, String stuclass, Date startTime, Date endTime) {
        // Retrieve student IDs for the class
        List<Students> students = studentsService.findStudentsByClass(stuclass);

        if (students.isEmpty()) {
            return false;
        }

        // Insert into Assignments table for each student
        for (Students student : students) {
            Assignments assignment = new Assignments();
            String Publisher_number = ThreadLocalUtil.get();
//            Publisher_number="111222333";
            assignment.setPublisher_number(Publisher_number);
            assignment.setStuNum(student.getStudent_number());
            assignment.setClass_number(student.getStuclass());
            assignment.setName(name);
            assignment.setAssignment_type(type);
            assignment.setStart_time(startTime);
            assignment.setEnd_time(endTime);
            assignment.setScore(BigDecimal.valueOf(0.0));
            assignment.setIsSubmit('n');
            assignment.setIsUse('y');

            assignmentsMapper.insertAssignment(assignment);
            Integer assignmentId = assignment.getId(); // 获取生成的 ID
            System.out.println(assignmentId + ")))))))))))))))");
            // Insert into AssignmentQuestions table
            for (Questions question : questions) {
                assignmentquestionsMapper.insertAssignmentQuestion(assignmentId, question.getId());
            }
        }

        return true;
    }


    @Override
    public boolean submitAnswers(Integer assignmentId, List<Map<String, Object>> userAnswers) {
        try {
            String stuNum = ThreadLocalUtil.get();
            int totalQuestions = userAnswers.size();
            int correctAnswers = 0;

            for (Map<String, Object> answer : userAnswers) {
                Integer questionId = (Integer) answer.get("id");
                String userAnswer = (String) answer.get("userAnswer");

                // Retrieve the correct answer from the Questions table
                Questions question = questionsMapper.selectById(questionId);
                String correctAnswer = question.getAnswer();

                // Determine if the user's answer is correct
                boolean isCorrect = userAnswer.equals(correctAnswer);
                if (isCorrect) {
                    correctAnswers++;
                }

                // Insert or update the answer in the database
                answersMapper.insertOrUpdateAnswer(assignmentId, questionId, userAnswer, stuNum, isCorrect ? "T" : "F");
            }

            // Calculate the score as a percentage
            BigDecimal score = BigDecimal.valueOf((double) correctAnswers / totalQuestions * 100);

            // Update the assignment with the score and set isSubmit to 'y'
            assignmentsMapper.updateAssignmentScoreAndStatus(assignmentId, score, "y");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void delete(Integer assId) {
        assignmentsMapper.delete(assId);
    }

    @Override
    public List<Assignments> getAllTypeList(String stuNumber, String type) {
        return assignmentsMapper.getAllTypeList(stuNumber,type);
    }

    @Override
    public List<Assignments> getTExamsOrAssignmentsList(String tNumber, String type) {
        return assignmentsMapper.getTExamsOrAssignmentsList(tNumber,type);
    }

    @Override
    public void Tdelete(String classNumber, String name) {
        assignmentsMapper.Tdelete(classNumber,name);
    }

    @Override
    public List<AssignmentsWithStudentName> getStuWorkListWithStudentNameByClass(String tNumber, String classNumber, String name) {
        return assignmentsMapper.getStuWorkListWithStudentNameByClass(tNumber,classNumber,name);
    }

    @Override
    public boolean checknameexist(String name) {
        return assignmentsMapper.findNameExist(name);
    }
}




